<!-- 
All rights Reserved, Designed By www.youyacao.com 
@Description:发布页面
@author:成都市一颗优雅草科技有限公司     
@version V3.7 
注意：本前端源码遵循 MulanPSL-2.0开源协议（木兰宽松许可证）本内容仅限于个人参考，禁止用于其他的商业用途
需要商业用途或者定制开发等可访问songshu.youyacao.com   联系QQ:422108995 23625059584
 -->
<template>
	<view class="body">
		<view class="status_bar"></view>
		<view class="head">
			<uni-icons color="#fff" size="30" type="arrowleft" @click="back" />
			<view class="publish-btn" @tap="_checkText(content)">
				<text>发布</text>
			</view>
		</view>
		<view class="content">
			<view class="content-wrapper">
				<textarea class="content-textarea" placeholder="说点什么..." v-model="content" />
			</view>
			<view class="right-icon-wrapper">
				<view class="add-item b-r-1" @tap="chooseVideo">
					<image class="right-icon" src="/static/img/video-icon.png"></image>
					<text>添加视频</text>
				</view>
				<view class="add-item" @tap="chooseImages">
					<image class="right-icon" src="/static/img/image-icon.png"></image>
					<text>添加图片</text>
				</view>
			</view>
			<view class="upload-file-list-wrapper" v-if="videoInfo.img!=undefined||imageInfo.length>0">
				<view class="file-wrapper video-file-wrapper" v-if="videoInfo.img!=undefined">
					<image class="file-img video-file-img" :src="formatUrl(videoInfo.img,5)" mode="aspectFill"></image>
				</view>
				<view class="file-wrapper image-file-wrapper" v-if="imageInfo.length>0">
					<image @click="previmg(imageInfo,index)" class="file-img image-file-img" v-for="(img,index) in imageInfo" :key="index"
					 :src="formatUrl(img,5)" mode="aspectFill"></image>
				</view>
			</view>
			<view class="type-wrapper" v-if="videoInfo.img !== undefined" @tap="showTypeList">
				<view class="type-select-wrapper">
					<view class="type-select-img-wrapper">
						<image class="type-select-img" src="/static/img/type.png" mode="widthFix"></image>
					</view>
					<view class="type-select-type-wrapper">
						<text class="type-select-type">{{ typeInfo.name === undefined ? '选择分类' : typeInfo.name }}</text>
					</view>
					<uni-icons type="forward" color="#fff" size="20"></uni-icons>
				</view>
			</view>
		</view>
		<view class="cu-load load-modal" v-if="uploadFile">
			<view class="gray-text">上传进度{{progress}}%</view>
		</view>
	</view>
</template>

<script>
	import uniIcons from "@/components/uni-icons/uni-icons.vue"
	import Test from '@/common/test.js'
	
	export default {
		components: {
			uniIcons,
		},
		data() {
			return {
				videoInfo: {},
				typeInfo: {},
				content: '',
				imageInfo: [],
				progress:0,
				uploadFile:false,
				machineResult: {
					Normal: "正常",
					Polity: "涉政",
					Sex: "色情",
					Terror: "暴恐",
					Legal: "违法违规",
					Ad: "广告"
				},
				loading: false
			};
		},
		onLoad() {
			uni.$on('selectType', (data) => {
				this.typeInfo = data;
			})
		},
		onUnload() {
			uni.$off('selectType');
		},
		methods: {
			previmg(urls, index) {
				urls = urls.map((item, key) => {
					return this.formatUrl(item)
				})
				uni.previewImage({
					current: index,
					indicator: "default",
					urls: urls,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							switch (data.tapIndex) {
								case 0: //保存图片
									uni.downloadFile({
										url: urls[data.index],
										success: (res) => {
											if (res.statusCode === 200) {
												uni.saveImageToPhotosAlbum({
													filePath: res.tempFilePath,
													success: function() {
														uni.showToast({
															title: "保存成功"
														});
													},
													fail: function() {
														uni.showToast({
															title: "保存失败，请稍后重试",
															icon: "none"
														});
													}
												});
											}
										}
									})
									break;
							}
						}
					}
				});
			},
			//格式化链接地址
			formatUrl(url, scale) {
				if (!scale) {
					scale = 1;
				}
				if (url == undefined) {
					return "";
				}
				var index = url.indexOf("http");
				if (index == 0) {
					return url;
				}
				return this.$store.state.baseUrl + "/thumb/" + scale + "?url=" + url;
			},
			back() {
				uni.navigateBack()
			},
			selectType(item) {
				this.typeInfo = item;
			},
			showTypeList() {
				const typeList = uni.getSubNVueById('typeList');
				typeList.show('slide-in-bottom', 200, () => {})
			},
			chooseVideo() {
				var that = this;
				var confirm = false;
				if (this.imageInfo.length > 0) {
					uni.showModal({
						content: '上传视频将清空图片列表，是否清空图片列表上传视频？',
						success: function(res) {
							if (res.confirm) {
								confirm = true;
								that.imageInfo = [];
							} else if (res.cancel) {
								confirm = false;
							}
						}
					});
					if (!confirm) {
						return;
					}
				}

				uni.chooseVideo({
					count: 1,
					compressed: false,
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePath
						//判断是否为七牛云存储
						if (this.config.use_qiniu == '1') {
							//如果是
							//获取Token
							this.$api.qiniuToken({}).then((res) => {
								//如果获取成功
								if (res.data.code == 0) {
									let token = res.data.data;
									var date = new Date();

									//开始上传
									const uploadTask = uni.uploadFile({
										url: 'https://upload-z2.qiniup.com', //该地址为华南空间地址。其他地区请更换为对应地区节点地址
										
										//需要对照地区可访问：https://doc.youyacao.com/web/#/4?page_id=341
										
										filePath: tempFilePath,
										dataType: 'json',
										name: 'file',
										formData: {
											'token': token,
											'key': this.user.id + "/" + date.getTime() + ".mp4"
										},
										success: (res) => {
											uni.hideLoading()
											this.uploadFile = false;
											this.progress=0;
											if (res.statusCode == 200) {
												var data = JSON.parse(res.data);
												if (!data.key) {
													uni.showToast({
														title: '上传失败,' + data.error,
														icon: 'none'
													});
													return;
												}
												uni.showToast({
													title: '上传成功',
												});
												//转换成服务器返回相同的数据结构
												var qiniuData = {
													'img': this.config.domain + data.key + "?vframe/png/offset/1",
													'url': this.config.domain + data.key
												}
												this.videoInfo = qiniuData;
											}
										},
										fail(e) {
											//console.log(e);
										}
									});
									
									uploadTask.onProgressUpdate((res) => {
										if(res.progress!=100){
											this.uploadFile = true;
											this.progress = res.progress;
										}
									});
								}
							})
							return;
							//调用上传
						}
						//如果不是,或者七牛云存储配置获取出错，调用正常上传
						//开始上传
						const uploadTask = uni.uploadFile({
							url: this.$config + 'api/api/upload',
							filePath: tempFilePath,
							dataType: 'json',
							name: 'file',
							formData: {
								'type': 'video'
							},
							success: (res) => {
								console.log("上传结果", res);
								uni.hideLoading()
								this.uploadFile = false;
								this.progress=0;
								if (res.statusCode == 200) {
									var data = JSON.parse(res.data);
									if (data.code == 1) {
										uni.showToast({
											title: '上传失败,' + data.msg,
											icon: 'none'
										});
										return;
									}
									uni.showToast({
										title: '上传成功',
									});
									this.videoInfo = data.data;
								}
							}
						});
						uploadTask.onProgressUpdate((res) => {
							if(res.progress!=100){
								this.uploadFile = true;
								this.progress = res.progress;
							}
						});

					},
					fail(res) {
						uni.showToast({
							title: '选择视频出现错误，请重新选择',
							icon: 'none'
						});
					}
				});
			},
			_checkImage(content) {
				Test('image', content).then(({ machine_result }) => {
					if (machine_result === 'Normal') {
						this.imageInfo.push(content)
					} else {
						const msg = this.machineResult[machine_result]
						uni.showToast({
							title: `检测到您的图片涉及${msg}，已自动删除。`,
							icon: 'none'
						})
						this.content = ''
					}
				})
			},
			_checkText(content) {
			
				if (content === '') {
					return uni.showToast({
						title: '说点什么吧',
						icon: 'none'
					})
				}
			
				Test('text', content).then(({ machine_result }) => {
					 console.log(333,machine_result)
					if (machine_result === 'Normal') {
						this.publish()
					} else {
						const msg = this.machineResult[machine_result]
						uni.showToast({
							title: `检测到您的文字内容涉及${msg}，请重新输入。`,
							icon: 'none'
						})
					}
				})
			},
			chooseImages() {
				var that = this;
				var confirm = false;
				if (this.videoInfo.img != undefined) {
					uni.showModal({
						content: '上传图片将不能上传视频，是否删除视频上传图片？',
						success: function(res) {
							if (res.confirm) {
								confirm = true;
								that.videoInfo = {};
							} else if (res.cancel) {
								confirm = false;
							}
						}
					});
					if (!confirm) {
						return;
					}
				}

				uni.chooseImage({
					count: 9 - this.imageInfo.length,
					sizeType: 'compressed',
					sourceType: ['album', 'camera'],
					success: (res) => {
						uni.showLoading({
							title: '正在上传中，请稍后',
							mask: false
						});

						const tempFilePaths = res.tempFilePaths;
						tempFilePaths.map((tempFilePath) => {
							//判断是否为七牛云存储
							if (this.config.use_qiniu == '1') {
								//如果是
								//获取Token
								this.$api.qiniuToken({}).then((res) => {
									console.log("qiniuToken=>", res);
									//如果获取成功
									if (res.data.code == 0) {
										let token = res.data.data;
										var date = new Date();
										//开始上传
										const uploadTask = uni.uploadFile({
											url: 'https://upload-z2.qiniup.com',
											filePath: tempFilePath,
											dataType: 'json',
											name: 'file',
											formData: {
												'token': token,
												'key': this.user.id + "/" + date.getTime() + "." + this.$utils.getFileExt(tempFilePath)
											},
											success: (res) => {
												console.log("上传结果", res);
												uni.hideLoading()
												this.uploadFile = false;
												this.progress=0;
												if (res.statusCode == 200) {
													var data = JSON.parse(res.data);
													if (!data.key) {
														uni.showToast({
															title: '上传失败,' + data.error,
															icon: 'none'
														});
														return;
													}
													uni.showToast({
														title: '上传成功',
													});
													this._checkImage(this.config.domain + data.key)
												}
											},
											fail(e) {
												//console.log(e);
											}
										});
										uploadTask.onProgressUpdate((res) => {
											if(res.progress!=100){
												this.uploadFile = true;
												this.progress = res.progress;
											}
										});
									}
								})
								return;
								//调用上传
							}
							//如果不是,或者七牛云存储配置获取出错，调用正常上传
							const uploadTask = uni.uploadFile({
								url: this.$config + 'api/api/upload', //仅为示例，非真实的接口地址
								filePath: tempFilePath,
								dataType: 'json',
								name: 'file',
								formData: {
									'type': 'img'
								},
								success: (res) => {
									console.log("上传结果", res);
									uni.hideLoading()
									this.uploadFile = false;
									this.progress=0;
									if (res.statusCode == 200) {
										var data = JSON.parse(res.data);
										if (data.code == 1) {
											uni.showToast({
												title: '上传失败,' + data.msg,
												icon: 'none'
											});
											return;
										}
										uni.showToast({
											title: '上传成功',
										});
										this.imageInfo.push(data.data.url);
									}
								},
								fail(e) {
									//console.log(e);
								}
							});
							uploadTask.onProgressUpdate((res) => {
								if(res.progress!=100){
									this.uploadFile = true;
									this.progress = res.progress;
								}
							});
						})
					},
					fail(res) {
						uni.showToast({
							title: '选择视频出现错误，请重新选择',
							icon: 'none'
						});
					}
				});
			},
			publish() {
				if (this.loading) return
				this.loading = true
				uni.showLoading({
					title: '发布中...',
					mask: false
				})
				let type = 0 //视频类型
				let textimagetype = 0;
				if (this.videoInfo.img == undefined && this.imageInfo.length == 0) {
					console.log("纯文本类型");
					type = 1; //图文类型
					textimagetype = 0;
				} else if (this.videoInfo.url != '' && this.videoInfo.url != undefined) {
					console.log("视频类型");
					type = 0;
				} else if (this.imageInfo.length > 0) {
					type = 1;
					console.log("图片类型");
					textimagetype = 1;
				} else {
					console.log("其他");
				}
				if (type == 0) {
					//判断是否选择分类
					if (this.typeInfo.name == '' || this.typeInfo.name == undefined) {
						uni.showToast({
							title: '请选择分类',
							icon: 'none'
						});
						return;
					}
					//开始提交发布请求
					this.$api.videoPublish({
						title: this.content,
						url: this.videoInfo.url,
						type: this.typeInfo.id
					}).then((res) => {
						this.loading = false
						if (res.data.code == 1) {
							uni.showToast({
								title: '发布失败,' + res.data.msg,
								icon: 'none'
							});
							return
						}
						uni.showToast({
							title: '发布成功,等待后台审核通过后方可查看',
							icon: 'none',
							duration: 2000,
							success: () => {
								setTimeout(() => {
									this.back()
								}, 2000)

							}
						})
					})
				} else if (type == 1) {
					//开始提交发布请求
					this.$api.textImageAdd({
						content: this.content,
						images: this.imageInfo.join(','),
						type: textimagetype
					}).then((res) => {
						this.loading = false
						if (res.data.code == 1) {
							uni.showToast({
								title: '发布失败,' + res.data.msg,
								icon: 'none'
							});
							return
						}
						uni.showToast({
							title: '发布成功,等待后台审核通过后方可查看',
							icon: 'none',
							duration: 2000,
							success: () => {
								setTimeout(() => {
									this.back()
								}, 2000)

							}
						})
					})
				}
			}
		},
		computed: {
			config() {
				return this.$store.state.config;
			},
			user() {
				return this.$store.state.user;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content-textarea {
		color: #FFFFFF;
	}
	.status_bar {
		height: var(--status-bar-height);
	}
	.body {
		background-color: #000;
		width: 100%;
		height: 100%;
	}
	.b-r-1 {
		border-right: 1rpx solid #999;
	}
	.add-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
	}

	.head {
		align-items: center;
		display: flex;
		height: 88rpx;
		justify-content: space-between;
		padding: 0 32rpx;
	}

	.search-wrapper {
		text-align: center;
		line-height: 76rpx;
		height: 76rpx;
		flex: 9.5;
		flex-direction: row;
		align-items: center;
		align-content: center;
		justify-content: center;

		text {
			line-height: 76rpx;
			height: 76rpx;
		}
	}

	.search {
		height: 88rpx;
		line-height: 88rpx;
		flex: 1;
	}

	.publish-btn {
		width: 114rpx;
		height: 48rpx;
		color: #FFFFFF;
		background: #fff;
		color: #333;
		font-size: 24rpx;
		border-radius: 24rpx;
		text-align: center;
		line-height: 48rpx;
	}

	.content {
		height: 800rpx;
		display: flex;
		flex-direction: column;
		position: relative;

		.content-wrapper {
			display: flex;
			margin: 32rpx;
			border-bottom: 1rpx solid #635A7E;
			padding-bottom: 32rpx;
			position: relative;
		}
		
		.right-icon-wrapper {
			display: flex;
			padding: 24rpx;
			.right-icon {
				width: 66rpx;
				height: 66rpx;
				margin-right: 24rpx;
			}
		}

		.type-wrapper {
			margin: 24rpx;
			
			.type-select-wrapper {
				display: flex;
				flex-direction: row;

				.type-select-img-wrapper {
					flex: 1;
					justify-content: center;
					align-items: center;
					display: flex;
					margin-right: 12rpx;

					.type-select-img {
						width: 36rpx;
						height: 36rpx;

					}
				}

				.type-select-type-wrapper {
					display: flex;
					flex: 10;
					align-items: center;
					font-size: 28rpx;
					color: #FFFFFF;
				}
			}
		}

		.button-btn-wrapper {
			margin-top: 420rpx;
			flex: 2;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-content: center;
			align-items: center;

			.cancel-btn {
				margin-left: 64rpx;
				flex: 4;
				color: $uni-text-color-active;
				font-size: 32rpx;
				border: 1rpx solid $uni-text-color-active;
				border-radius: 50rpx;

				&.button-hover {
					background-color: rgba($color: #000000, $alpha: .1);
				}
			}


		}

		.upload-file-list-wrapper {
			margin: 24rpx;
		}

		.file-wrapper {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			flex-wrap: wrap;
			margin-right: -12rpx;
			margin-bottom: -12rpx;
		}

		.file-img {
			flex: 4;
			min-width: 30vw;
			max-width: 229rpx;
			max-height: 235rpx;
			margin-right: 12rpx;
			margin-bottom: 12rpx;
		}
	}
</style>
